package org.iWMS.core.service;

import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.iWMS.core.domain.User;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: issuser
 * Date: 13-5-4
 * Time: 下午3:42
 * To change this template use File | Settings | File Templates.
 */
public class ShiroDbRealm extends AuthorizingRealm {
    private final static Logger logger=Logger.getLogger(ShiroDbRealm.class);
    protected UserService userService;

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    /**
     * 认证回调函数,登录时调用.
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        logger.debug(token.getUsername() + "认证用户权限");
        User user = userService.findUserByUserName(token.getUsername());
        if (user != null) {
            logger.debug(token.getUsername() + "认证用户权限成功");
            return new SimpleAuthenticationInfo(user.getUserName(),user.getPassword(), getName());
        } else {
            logger.debug(token.getUsername() + "认证用户权限失败");
            return null;
        }
    }

    /**
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();
        User user = userService.findUserByUserName(username);
        user.setRoleList(new ArrayList());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(user.getRoleList());
        return info;
    }

}
